<!--
	THIS EXAMPLE WAS DOWNLOADED FROM https://echarts.apache.org/examples/zh/editor.html?c=candlestick-brush
-->
<!DOCTYPE html>
<html lang="zh-CN" style="height: 100%">
<head>
    <meta charset="utf-8">
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 99.9%"></div>

<script type="text/javascript" src="js/jquery-3.6.0.js"></script>
<script type="text/javascript" src="js/echarts.js"></script>
<script type="text/javascript" src="js/my.js"></script>
<script type="text/javascript" src="js/Tool.js"></script>
<!-- Uncomment this line if you want to dataTool extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.2/dist/extension/dataTool.min.js"></script>
-->
<!-- Uncomment this line if you want to use gl extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts-gl@2/dist/echarts-gl.min.js"></script>
-->
<!-- Uncomment this line if you want to echarts-stat extension
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts-stat@latest/dist/ecStat.min.js"></script>
-->
<!-- Uncomment this line if you want to use map
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/china.js"></script>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@4.9.0/map/js/world.js"></script>
-->
<!-- Uncomment these two lines if you want to use bmap extension
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=YOUR_API_KEY"></script>
<script type="text/javascript" src="https://fastly.jsdelivr.net/npm/echarts@5.3.2/dist/extension/bmap.min.js"></script>
-->

<script type="text/javascript">

    var code = getUrlParam('code');
    if (!code) {
        window.location.replace("?code=000005.SZ")
    }
    var dom = document.getElementById('container');
    var myChart = echarts.init(dom, "dark", {
        renderer: 'canvas',
        useDirtyRect: false
    });
    var app = {};
    // var ROOT_PATH = 'https://fastly.jsdelivr.net/gh/apache/echarts-website@asf-site/examples';
    var ROOT_PATH = 'http://localhost:5000';
    // var ROOT_PATH = '';
    var option;

    // const upColor = '#ec0000';
    // const downColor = '#00da3c';
    var bgColor = "#1f212d";//背景
    var upColor = "#F9293E";//涨颜色
    var downColor = "#00aa3b";//跌颜色

    function splitData(rawData) {
        let categoryData = [];
        let values = [];
        let volumes = [];
        let closes = [];
        for (let i = 0; i < rawData.length; i++) {
            categoryData.push(rawData[i].splice(0, 1)[0]);
            values.push(rawData[i]);
            closes.push(rawData[i][2]);
            volumes.push([i, rawData[i][4], rawData[i][0] > rawData[i][1] ? 1 : -1]);
        }
        return {
            categoryData: categoryData,
            values: values,
            volumes: volumes,
            closes: closes
        };
    }

    function calculateMA(dayCount, data) {
        var result = [];
        for (var i = 0, len = data.values.length; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < dayCount; j++) {
                sum += data.values[i - j][2];
            }
            result.push(+(sum / dayCount).toFixed(3));
        }
        return result;
    }

    var calcEMA, calcDIF, calcDEA, calcMACD;

    /*
     * 计算EMA指数平滑移动平均线，用于MACD
     * @param {number} n 时间窗口
     * @param {array} data 输入数据
     * @param {string} field 计算字段配置
     */
    calcEMA = function (n, data, field) {
        var i, l, ema, a;
        a = 2 / (n + 1);
        if (field) {
            //二维数组
            ema = [data[0][field]];
            for (i = 1, l = data.length; i < l; i++) {
                ema.push((a * data[i][field] + (1 - a) * ema[i - 1]).toFixed(2));
            }
        } else {
            //普通一维数组
            ema = [data[0]];
            for (i = 1, l = data.length; i < l; i++) {
                ema.push((a * data[i] + (1 - a) * ema[i - 1]).toFixed(3));
            }
        }
        return ema;
    };

    /*
     * 计算DIF快线，用于MACD
     * @param {number} short 快速EMA时间窗口
     * @param {number} long 慢速EMA时间窗口
     * @param {array} data 输入数据
     * @param {string} field 计算字段配置
     */
    calcDIF = function (short, long, data, field) {
        var i, l, dif, emaShort, emaLong;
        dif = [];
        emaShort = calcEMA(short, data, field);
        emaLong = calcEMA(long, data, field);
        for (i = 0, l = data.length; i < l; i++) {
            dif.push((emaShort[i] - emaLong[i]).toFixed(3));
        }
        return dif;
    };

    /*
     * 计算DEA慢线，用于MACD
     * @param {number} mid 对dif的时间窗口
     * @param {array} dif 输入数据
     */
    calcDEA = function (mid, dif) {
        return calcEMA(mid, dif);
    };

    /*
     * 计算MACD
     * @param {number} short 快速EMA时间窗口
     * @param {number} long 慢速EMA时间窗口
     * @param {number} mid dea时间窗口
     * @param {array} data 输入数据
     * @param {string} field 计算字段配置
     */
    calcMACD = function (short, long, mid, data, field) {
        var i, l, dif, dea, macd, result;
        result = {};
        macd = [];
        dif = calcDIF(short, long, data, field);
        dea = calcDEA(mid, dif);
        for (i = 0, l = data.length; i < l; i++) {
            // macd.push(((dif[i] - dea[i]) * 2).toFixed(3));
            var val = ((dif[i] - dea[i]) * 2).toFixed(3)
            macd.push([i, val, val > 0 ? 1 : -1]);
        }
        result.dif = dif;
        result.dea = dea;
        result.macd = macd;
        return result;
    };

    function calculateKDJ(data, period, smooth) {
        var close = [];
        var high = [];
        var low = [];
        var kdj = {k: [], d: [], j: []}
        for (const item of data) {
            close.push(item[1])
            low.push(item[2])
            high.push(item[3])
        }

        // const kdj = [];
        for (let i = 0; i < close.length; i++) {
            const c = close[i];
            const h = high[i];
            const l = low[i];

            let rsv;
            if (i < period) {
                rsv = 100 * (c - l) / (h - l);
            } else {
                const _h = Math.max(...high.slice(i - period, i));
                const _l = Math.min(...low.slice(i - period, i));
                rsv = 100 * (c - _l) / (_h - _l);
            }

            let k, d, j;
            if (i === 0) {
                k = rsv;
                d = rsv;
                j = rsv;
            } else {
                const prevK = kdj.k[i - 1];
                const prevD = kdj.d[i - 1];
                k = (1 - 1 / smooth) * prevK + 1 / smooth * rsv;
                d = (1 - 1 / smooth) * prevD + 1 / smooth * k;
                j = 3 * k - 2 * d;
            }
            // kdj.push([k, d, j]);
            kdj.k.push(parseFloat(k.toFixed(3)));
            kdj.d.push(parseFloat(d.toFixed(3)));
            kdj.j.push(parseFloat(j.toFixed(3)));
        }
        return kdj;
    }

    // function drawBollIndicator(code, data) {
    //     // $.ajax({
    //     //     type: "get",
    //     //     url: ROOT_PATH + '/indicator?stg=BollStg&code=' + code,
    //     //     // url: ROOT_PATH + '/data?code=' + code,
    //     //     // data: {name: "张三"},
    //     //     // dataType: "json",
    //     //     success: function (data) {
    //     //         alert("正确");
    //     //     },
    //     //
    //     //     error: function (err) {
    //     //         alert("错误");
    //     //     }
    //     // });
    //     $.get(ROOT_PATH + '/indicator?stg=BollStg&code=' + code, function (rawData) {
    //         var options1 = {
    //             series: [
    //                 {
    //                     name: 'upperband',
    //                     type: 'line',
    //                     data: rawData.upperband,
    //                     smooth: true,
    //                     showSymbol: false,
    //                     lineStyle: {
    //                         width: 1
    //                     },
    //                 },
    //                 {
    //                     name: 'middleband',
    //                     type: 'line',
    //                     data: rawData.middleband,
    //                     smooth: true,
    //                     showSymbol: false,
    //                     lineStyle: {
    //                         width: 1
    //                     },
    //                 },
    //                 {
    //                     name: 'lowerband',
    //                     type: 'line',
    //                     data: rawData.lowerband,
    //                     smooth: true,
    //                     showSymbol: false,
    //                     lineStyle: {
    //                         width: 1
    //                     },
    //                 }
    //             ]
    //         };
    //         var options2 = {
    //             title: {
    //                 text: 'Echarts动态更新数据'
    //             },
    //             tooltip: {},
    //             legend: {
    //                 data: ['销量']
    //             },
    //             //设置X轴
    //             xAxis: {
    //                 data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
    //             },
    //             yAxis: {},
    //             series: [
    //                 {
    //                     name: 'upperband',
    //                     type: 'line',
    //                     // data: rawData.upperband,
    //                     data: calculateMA(60, data),
    //                     smooth: true,
    //                     showSymbol: false,
    //                     lineStyle: {
    //                         width: 1
    //                     },
    //                 },
    //             ]
    //         };
    //         console.log("哈哈哈哈哈哈")
    //         myChart.setOption(options1)
    //     }).fail(function () {
    //         window.alert("请求指标失败,请检查服务器是否打开, " + ROOT_PATH);
    //     });
    // }

    function calculateBollingerBands(data, period, deviation) {
        var bollingerBands = [];
        let middles = [];
        let uppers = [];
        let lowers = [];
        for (var i = 1; i < period; i++) {
            middles.push(null);
            uppers.push(null);
            lowers.push(null);
        }
        for (var i = period - 1; i < data.length; i++) {
            var sum = 0;
            for (var j = i - period + 1; j <= i; j++) {
                sum += data[j];
            }
            var average = sum / period;
            var variance = 0;
            for (var j = i - period + 1; j <= i; j++) {
                variance += Math.pow(data[j] - average, 2);
            }
            variance /= period;
            var standardDeviation = Math.sqrt(variance);
            var upperBand = average + deviation * standardDeviation;
            var lowerBand = average - deviation * standardDeviation;
            middles.push(average.toFixed(2));
            uppers.push(upperBand.toFixed(2));
            lowers.push(lowerBand.toFixed(2));
            if (lowerBand > data[i]) {
                console.log("lower,close:", lowerBand, data[i])
            }

        }
        return {
            middle: middles,
            upper: uppers,
            lower: lowers,
        };
    }


    $.get(ROOT_PATH + '/data?code=' + code, function (rawData) {
        // console.log(rawData);
        var data2 = rawData['data'];    //row: date, open, close, low, high, vol
        var data3 = {};
        for (i in data2) {
            data3[data2[i][0]] = data2[i];
        }
        var trade = tool.reEChartTrade(rawData['trade'], data3)

        var data = splitData(data2);
        var temp = calculateMA(10, data);
        var macd = calcMACD(12, 26, 9, data.values, 1);
        var kdj = calculateKDJ(data.values, 9, 3)
        // drawBollIndicator(code, data)
        // console.log(temp, macd.macd, data.volumes);
        // console.log(kdj, macd, kdj.k);
        // console.log(kdj.k);
        var boll = calculateBollingerBands(data.closes, 20, 2)

        myChart.setOption(
            (option = {
                backgroundColor: bgColor,
                animation: false,
                // legend: {
                //     bottom: 10,
                //     left: 'center',
                //     data: ['日k', 'MA1', 'MA10', 'MA25']
                // },
                legend: { //图例控件,点击图例控制哪些系列不显示
                    icon: 'rect',
                    type: 'scroll',
                    itemWidth: 14,
                    itemHeight: 2,
                    left: 10,
                    top: '0%',
                    animation: true,
                    textStyle: {
                        fontSize: 12,
                        color: '#0e99e2'
                    },
                    pageIconColor: '#0e99e2'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross'
                    },
                    borderWidth: 1,
                    borderColor: '#ccc',
                    padding: 10,
                    textStyle: {
                        color: '#000'
                    },
                    position: function (pos, params, el, elRect, size) {
                        const obj = {
                            top: 10
                        };
                        obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                        return obj;
                    }
                    // extraCssText: 'width: 170px'
                },
                axisPointer: {
                    show: true,
                    link: [
                        {
                            xAxisIndex: 'all'
                        }
                    ],
                    label: {
                        backgroundColor: '#777'
                    }
                },
                toolbox: {
                    feature: {
                        dataZoom: {
                            yAxisIndex: false
                        },
                        brush: {
                            type: ['lineX', 'clear']
                        }
                    }
                },
                brush: {
                    xAxisIndex: 'all',
                    brushLink: 'all',
                    outOfBrush: {
                        colorAlpha: 0.1
                    }
                },
                visualMap: {
                    show: false,
                    seriesIndex: 5,
                    dimension: 2,
                    pieces: [
                        {
                            value: 1,
                            color: upColor
                        },
                        {
                            value: -1,
                            color: downColor
                        }
                    ]
                },
                grid: [
                    {
                        left: '10%',
                        right: '8%',
                        height: '35%'
                    },
                    {
                        left: '10%',
                        right: '8%',
                        top: '35%',
                        height: '15%'
                    },
                    {
                        left: '10%',
                        right: '8%',
                        top: '50%', //MACD 指标
                        height: '15%'
                    },
                    {
                        left: '10%',
                        right: '8%',
                        top: '65%', //kdj 指标
                        height: '15%'
                    }
                ],
                xAxis: [
                    {
                        type: 'category',
                        data: data.categoryData,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        splitLine: {show: false},
                        min: 'dataMin',
                        max: 'dataMax',
                        axisPointer: {
                            z: 100
                        }
                    },
                    {
                        type: 'category',
                        gridIndex: 1,
                        data: data.categoryData,
                        boundaryGap: false,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: {show: false},
                        min: 'dataMin',
                        max: 'dataMax'
                    },
                    { //macd
                        type: 'category',
                        gridIndex: 2,
                        data: data.categoryData,
                        axisLabel: {
                            show: false
                        }
                    },
                    { //kdj
                        type: 'category',
                        gridIndex: 3,
                        data: data.categoryData,
                        axisLabel: {
                            show: false
                        }
                    }
                ],
                yAxis: [
                    {
                        scale: true,
                        splitArea: {
                            show: true
                        }
                    },
                    {
                        scale: true,
                        gridIndex: 1,
                        splitNumber: 2,
                        axisLabel: {show: false},
                        axisLine: {show: false},
                        axisTick: {show: false},
                        splitLine: {show: false}
                    },
                    { //幅图
                        z: 4, gridIndex: 2, splitNumber: 4,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: { //label文字设置
                            // show:false,
                            color: '#c7c7c7',
                            inside: true, //label文字朝内对齐
                            fontSize: 8
                        },
                    },
                    { //幅图
                        // z: 4,
                        // splitNumber: 4,
                        gridIndex: 3,
                        axisLine: {onZero: false},
                        axisTick: {show: false},
                        splitLine: {show: false},
                        axisLabel: { //label文字设置
                            // show:false,
                            color: '#c7c7c7',
                            inside: true, //label文字朝内对齐
                            fontSize: 8
                        },
                    }
                ],
                dataZoom: [
                    {
                        type: 'inside',
                        xAxisIndex: [0, 1, 2, 3],
                        start: 98,
                        end: 100
                    },
                    {
                        show: true,
                        xAxisIndex: [0, 1, 2, 3],
                        type: 'slider',
                        top: '94%',
                        start: 98,
                        end: 100
                    }
                    // {
                    //     type: 'slider',
                    //     xAxisIndex: [0, 1, 2], //控件联动
                    //     start: 100,
                    //     end: 80,
                    //     throttle: 10,
                    //     top: '94%',
                    //     height: '6%',
                    //     borderColor: '#696969',
                    //     textStyle: {
                    //         color: '#dcdcdc'
                    //     },
                    //     handleSize: '90%', //滑块图标
                    //     handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    //     dataBackground: {
                    //         lineStyle: {
                    //             color: '#fff'
                    //         }, //数据边界线样式
                    //         areaStyle: {
                    //             color: '#696969'
                    //         } //数据域填充样式
                    //     }
                    // },
                ],
                blendMode: 'source-over',
                series: [
                    {
                        name: '日k',
                        type: 'candlestick',
                        data: data.values,
                        itemStyle: {
                            color: upColor,
                            color0: downColor,
                            borderColor: undefined,
                            borderColor0: undefined
                        },
                        tooltip: {
                            formatter: function (param) {
                                param = param[0];
                                return [
                                    'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                                    'Open: ' + param.data[0] + '<br/>',
                                    'Close: ' + param.data[1] + '<br/>',
                                    'Lowest: ' + param.data[2] + '<br/>',
                                    'Highest: ' + param.data[3] + '<br/>'
                                ].join('');
                            }
                        },
                        markPoint: {
                            label: {
                                formatter: function (param) {
                                    return param != null ? Math.round(param.value) + '' : '';
                                }
                            },
                            data: trade,
                            // [
                            //     {
                            //         name: 'Mark',
                            //         coord: ['2018-12-12', 28],
                            //         value: 30,
                            //         itemStyle: {
                            //             color: 'green'
                            //         }
                            //     },
                            // ],
                            tooltip: {
                                formatter: function (param) {
                                    return param.name + '<br>' + (param.data.coord || '');
                                }
                            }
                        },

                    },
                    // {
                    //     name: 'MA1',
                    //     type: 'line',
                    //     data: calculateMA(1, data),
                    //     smooth: true,
                    //     showSymbol: false,
                    //     lineStyle: {
                    //         width: 1
                    //     },
                    // },
                    // {
                    //     name: 'MA2',
                    //     type: 'line',
                    //     data: calculateMA(2, data),
                    //     smooth: true,
                    //     showSymbol: false,
                    //     lineStyle: {
                    //         width: 1
                    //     },
                    // },
                    // {
                    //     name: 'MA10',
                    //     type: 'line',
                    //     data: calculateMA(10, data),
                    //     smooth: true,
                    //     showSymbol: false,
                    //     lineStyle: {
                    //         width: 1
                    //     }
                    // },
                    {
                        name: 'MA25',
                        type: 'line',
                        data: calculateMA(5, data),
                        smooth: false,
                        showSymbol: false,
                        lineStyle: {
                            width: 1
                        }
                    },
                    {
                        name: 'bollUpper',
                        type: 'line',
                        data: boll.upper,
                        smooth: true,
                        showSymbol: false,
                        lineStyle: {
                            width: 1
                        }
                    },
                    {
                        name: 'bollMiddle',
                        type: 'line',
                        data: boll.middle,
                        smooth: true,
                        showSymbol: false,
                        lineStyle: {
                            width: 1
                        }
                    },
                    {
                        name: 'bollLower',
                        type: 'line',
                        data: boll.lower,
                        smooth: true,
                        showSymbol: false,
                        lineStyle: {
                            width: 1
                        }
                    },
                    {
                        name: 'Volume',
                        type: 'bar',
                        xAxisIndex: 1,
                        yAxisIndex: 1,
                        data: data.volumes,
                        // data: macd.macd,
                    },
                    {
                        name: 'MACD',
                        type: 'bar',
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: macd.macd,
                        barWidth: '40%',
                        itemStyle: {
                            normal: {
                                color: function (params) {
                                    var colorList;
                                    if (params.data >= 0) {
                                        colorList = upColor;
                                    } else {
                                        colorList = downColor;
                                    }
                                    return colorList;
                                },
                            }
                        }
                    },
                    {
                        name: 'DIF',
                        type: 'line',
                        symbol: "none",
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: macd.dif,
                        lineStyle: {
                            normal: {
                                color: '#da6ee8',
                                width: 1
                            }
                        }
                    },
                    {
                        name: 'DEA',
                        type: 'line',
                        symbol: "none",
                        xAxisIndex: 2,
                        yAxisIndex: 2,
                        data: macd.dea,
                        lineStyle: {
                            normal: {
                                opacity: 0.8,
                                color: '#39afe6',
                                width: 1
                            }
                        }
                    },
                    {
                        name: 'kdj.k',
                        type: 'line',
                        symbol: "none",
                        xAxisIndex: 3,
                        yAxisIndex: 3,
                        data: kdj.k,
                        lineStyle: {
                            normal: {
                                opacity: 0.8,
                                color: '#f7fafc',
                                width: 1
                            }
                        }
                    },
                    {
                        name: 'kdj.d',
                        type: 'line',
                        symbol: "none",
                        xAxisIndex: 3,
                        yAxisIndex: 3,
                        data: kdj.d,
                        lineStyle: {
                            normal: {
                                opacity: 0.8,
                                color: '#fcca04',
                                width: 1
                            }
                        }
                    },
                    {
                        name: 'kdj.j',
                        type: 'line',
                        symbol: "none",
                        xAxisIndex: 3,
                        yAxisIndex: 3,
                        data: kdj.j,
                        lineStyle: {
                            normal: {
                                opacity: 0.8,
                                color: '#d20680',
                                width: 1
                            }
                        }
                    }
                ]
            }),
            true
        );
        // myChart.dispatchAction({
        //     type: 'brush',
        //     areas: [
        //         {
        //             brushType: 'lineX',
        //             coordRange: ['2016-06-02', '2016-06-20'],
        //             xAxisIndex: 0
        //         }
        //     ]
        // });
    }).fail(function () {
        window.alert("请求失败,请检查服务器是否打开, " + ROOT_PATH);
    });

    if (option && typeof option === 'object') {
        myChart.setOption(option);
    }

    window.addEventListener('resize', myChart.resize);
</script>
</body>
</html>